﻿using DevExpress.XtraBars;
using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Collections.Generic;
using System.Linq;
using DataProcess.Core.DataAccess;
using DataProcess.Core.Model;
using DataProcess.Core.Model.Tqms;
using DataProcess.Core.Tools;
using DataProcess.Core.Enums;
using DataProcess.Interface;

namespace DataProcess.Views
{
    public partial class SystemSettingForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        protected virtual DbContext<SystemSetting> DBContext { get; set; }

        /// <summary>
        /// 数据状态
        /// </summary>
        public DataEditType DataEditType { get; private set; }

        public Action<SystemSetting> Updated;

        /// <summary>
        /// 旧数据
        /// </summary>
        public SystemSetting OldItem { get; private set; }

        /// <summary>
        /// 新数据
        /// </summary>
        public SystemSetting NewItem { get; private set; }
        public SystemSettingForm()
        {
            DBContextInit();
            InitializeComponent();
            var result = DBContext.CurrentDb.GetList();
            SystemSetting item;
            if (result == null || result.Count == 0)
            {
                DataEditType = DataEditType.Add;
                item = new SystemSetting();
            }
            else
            {
                DataEditType = DataEditType.Modify;
                item = result[0];
            }
            Initialize(item);
        }

        private void CmbPlant_EditValueChanged(object sender, EventArgs e)
        {
            if (sender is LookUpEdit edit)
            {
                TqmsPressDictionaryInfo info = (TqmsPressDictionaryInfo)edit.GetSelectedDataRow();
                if (info != null)
                {
                    NewItem.TargetCode = info.itemvalue;
                    NewItem.TargetName = info.itemname;
                }
            }
        }

        protected virtual void DBContextInit()
        {
            DBContext = new DbContext<SystemSetting>();
        }

        public virtual void Initialize(SystemSetting item)
        {
            NewItem = new SystemSetting();
            if (item == null)
            {
                OldItem = new SystemSetting();
            }
            else
            {
                OldItem = item;
            }
            var json = item.ToJson();
            OldItem = json.FromJson<SystemSetting>();
            NewItem = json.FromJson<SystemSetting>();
        }

        protected void DataDetailsForm_Load(object sender, EventArgs e)
        {
            DetailsLayout.DataSource = NewItem;
            if (DataEditType == DataEditType.Modify)
            {
                repositoryItemLookUpEdit1.DataSource = NewItem.AnalysisMappingList.Select(it => new TqmsAssayItemInfo() { assItem = it.TargetName, assItemu = it.TargetName, fidId = it.TargetName, itemType = it.TargetName });
            }
        }

        protected void DataDetailsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// 通过设置的HttpEndPoint请求数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnRequest_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(NewItem.EndpointAnalysisItem) || string.IsNullOrEmpty(NewItem.EndpointDataDictionary))
            {
                OperatorInfoResult("请先完善【测量项目Endpoint】或【数据字典Endpoint】");
                return;
            }

            HttpHelper http = new HttpHelper();
            try
            {
                var analysisItem = http.Get<TqmsHttpResult<List<TqmsAssayItemInfo>>>(NewItem.EndpointAnalysisItem, NewItem.Author);
                if (analysisItem != null && analysisItem.data != null)
                {
                    this.repositoryItemLookUpEdit1.DataSource = analysisItem.data;
                    this.repositoryItemLookUpEdit1.ForceInitialize();
                }
                else
                {
                    OperatorWaringResult($"请求测量项目数据失败,请检查对应的Endpoint地址是否填写正确.返回信息为：{analysisItem.code}");
                    return;
                }
            }
            catch (Exception ex)
            {
                OperatorErrorResult(ex.Message);
            }
            finally
            {
                http.Dispose();
            }
        }

        protected void Save_BBI_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (OperatorInfoResult($"确定执行该操作么?点击\"确定\"会将数据{(DataEditType == DataEditType.Add ? "新增" : "更新")}至数据库!") != DialogResult.OK)
            {
                return;
            }
            DataSave();
        }

        protected void SaveAndClose_BBI_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (OperatorInfoResult($"确定执行该操作么?点击\"确定\"会将数据{(DataEditType == DataEditType.Add ? "新增" : "更新")}至数据库并关闭该窗体") != DialogResult.OK)
            {
                return;
            }

            DataSave(false);
            DialogResult = DialogResult.OK;
        }

        protected void Reset_BBI_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (OperatorWaringResult("确定执行该操作么?点击\"确定\"将撤销所有更改!", "警告") == DialogResult.OK)
            {
                NewItem = OldItem.ToJson().FromJson<SystemSetting>();
                DetailsLayout.DataSource = NewItem;
            }
        }

        protected void DataSave(bool SavedMsg = true)
        {
            if (!DetailsLayout.Validate()) return;
            var g = NewItem.AnalysisMappingList.GroupBy(it => it.SourceName);
            foreach (var item in g)
            {
                if (item.Count() > 1)
                {
                    OperatorWaringResult($"源名称【{item.Key}】有重复项，请检查并更改后再提交");
                    return;
                }
            }

            switch (DataEditType)
            {
                case DataEditType.Add:
                    DataInsert(SavedMsg);
                    break;
                case DataEditType.Modify:
                    DataUpdate(SavedMsg);
                    break;
            }
        }

        protected void DataInsert(bool SavedMsg = true)
        {
            try
            {
                if (DBContext.CurrentDb.Insert(NewItem))
                {
                    Updated?.Invoke(NewItem);
                    if (SavedMsg) OperatorInfoResult("保存成功!");
                    DataEditType = DataEditType.Modify;
                }
                else
                {
                    OperatorWaringResult("保存失败");
                }
            }
            catch (Exception ex)
            {
                OperatorErrorResult(ex.Message);
            }
        }

        protected void DataUpdate(bool SavedMsg = true)
        {
            try
            {
                if (DBContext.CurrentDb.Update(NewItem))
                {
                    Updated?.Invoke(NewItem);
                    if (SavedMsg) OperatorInfoResult("保存成功!");
                }
                else
                {
                    OperatorWaringResult("保存失败");
                }
            }
            catch (Exception ex)
            {
                OperatorErrorResult(ex.Message);
            }
        }

        protected DialogResult OperatorWaringResult(string test, string caption = "警告")
        {
            return XtraMessageBox.Show(this, test, caption, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
        }

        protected DialogResult OperatorErrorResult(string test, string caption = "错误")
        {
            return XtraMessageBox.Show(this, test, caption, MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
        }

        protected DialogResult OperatorInfoResult(string test, string caption = "提示")
        {
            return XtraMessageBox.Show(this, test, caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void CMSAdd_Click(object sender, EventArgs e)
        {
            NewItem.AnalysisMappingList.Add(new AnalysisItemMapping());
            AnalysisMappingListGridControl.RefreshDataSource();
        }

        private void CMSDelete_Click(object sender, EventArgs e)
        {
            if (OperatorInfoResult("确定要删除该条映射么？") == DialogResult.OK)
            {
                gridMapping.DeleteSelectedRows();
            }
        }
    }
}


//http://dstbj.jdsn.com.cn:8072/TqmsInterface/PressDictionaryInfo
//http://dstbj.jdsn.com.cn:8072/TqmsInterface/AssayItemInfo

//http://dstbj.jdsn.com.cn:8072/TqmsInterface/YgyResultInfo

//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJJZGVTdHVkaW8iLCJ1c2VyVHlwZSI6IjEiLCJhY2NvdW50IjoiMTY1NDQ3NjMzMjY1NSJ9.zzeI3OP_nhXyw_YSXPBFSBHBN6r1bwdVhw4hY90ZL20